class Solution {
public:

    int search(vector<int>& nums1, vector<int>& nums2, int k)
    {
        int index1 = 0, index2 = 0;
        int m = nums1.size(), n = nums2.size();
        while (true)
        {
            if (index1 == m)
            {
                return nums2[index2 + k - 1];//数组一已经到达边界,直接返回数值二加需要剩余排除数
            }
            else if (index2 == n)
            {
                return nums1[index1 + k - 1];
            }

            if (k == 1)return min(nums1[index1], nums2[index2]);

            int nextIndex1 = min(index1 + k / 2 - 1, m - 1);
            int nextIndex2 = min(index2 + k / 2 - 1, n - 1);
            if (nums1[nextIndex1] > nums2[nextIndex2])
            {
                k -= nextIndex2 - index2 + 1;//数组二可以直接排除这一部分
                index2 = nextIndex2 + 1;//排除后需要更新位置
            }
            else
            {
                k -= nextIndex1 - index1 + 1;
                index1 = nextIndex1 + 1;
            }
        }
    }

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
    {
        int n = nums1.size() + nums2.size();
        if (n % 2 == 1)
        {
            return search(nums1, nums2, n / 2 + 1);
        }
        else
        {
            return (search(nums1, nums2, n / 2) + search(nums1, nums2, n / 2 + 1)) / 2.0;
        }
    }
};